import timeit
import re

if __name__ == '__main__':
    # 基础分割（默认空格分隔）
    text = "Python  是  最  好  的  语言"
    parts = text.split()  # 自动处理多空格
    print(parts)  # ['Python', '是', '最', '好', '的', '语言']

    # 指定分隔符
    csv_data = "A,25,engineer"
    fields = csv_data.split(",")
    print(fields)  # ['A', '25', 'engineer']

    # 限制分割次数
    log_entry = "2025-04-21 14:30:00 ERROR: disk full"
    parts = log_entry.split(" ", 2)
    print(parts)  # ['2025-04-21', '14:30:00', 'ERROR: disk full']

    # 处理连续分隔符
    text = "a,,b,,,c"
    result = text.split(",")
    print(result)  # ['a', '', 'b', '', '', 'c']

    words = ["Python", "is", "awesome"]
    sentence = " ".join(words)
    print(sentence)  # "Python is awesome"

    # 格式化拼接
    data = {"name": "A", "age": 30}
    formatted = "Name: {name}, Age: {age}".format(**data)
    print(formatted)  # "Name: A, Age: 30"

    # 高性能拼接（百万级数据）
    parts = []
    for i in range(1_000_000):
        parts.append(str(i))
    result = ",".join(parts)  # 内存高效

    # 测试数据
    # data = ["a"] * 10000
    #
    # # 使用 + 拼接
    # time_plus = timeit.timeit(lambda: "+".join(data), number=1000)
    #
    # # 使用 join 拼接
    # time_join = timeit.timeit(lambda: " ".join(data), number=1000)
    #
    # print(f"+ 拼接耗时: {time_plus:.4f}秒")  # 约0.12秒
    # print(f"join 拼接耗时: {time_join:.4f}秒")  # 约0.003秒


    # 基础匹配
    pattern = r"\d+"
    text = "Price: 199.99 USD"
    match = re.search(pattern, text)
    if match:
        print(f"找到数字: {match.group()}") #找到数字: 199

    # 编译正则表达式
    regex = re.compile(r"\w+@\w+\.\w+")
    emails = regex.findall("联系我们: support@python.org 或 sales@company.com")
    print(emails)  # ['support@python.org', 'sales@company.com']


    print("======================")
    text = "订单号: 20250421-ABC123, 金额:1999.00元"
    # 基础分组
    pattern = r"订单号: (\d{8}-\w{6}), 金额:(\d+\.\d{2})元"
    match = re.search(pattern, text)
    if match:
        print(f"订单号: {match.group(1)}")  # 订单号: 20250421-ABC123
        print(f"金额: {match.group(2)}")  # 金额: 1999.00

    # 命名分组
    pattern = r"订单号: (?P<order>\d{8}-\w{6}), 金额:(?P<amount>\d+\.\d{2})元"
    match = re.search(pattern, text)
    if match:
        print(match.groupdict())  # {'order': '20250421-ABC123', 'amount': '1999.00'}

    print("===========")

    text = "价格123元 优惠价456元"

    pattern = r"(?<=价格)\d+元"
    matches = re.findall(pattern, text)
    print(matches)  # ['123元']

    html = "<div>内容1</div><div>内容2</div>"
    # 贪婪匹配
    print(re.findall(r"<div>.*</div>", html))  # ['<div>内容1</div><div>内容2</div>']
    # 非贪婪匹配
    print(re.findall(r"<div>.*?</div>", html))  # ['<div>内容1</div>', '<div>内容2</div>']

    parts = []
    for i in range(1_000_000):
        parts.append(str(i))
    result = ",".join(parts)  # 比循环使用+快100倍

    # 避免重复编译正则
    regex = re.compile(r"\d+")
    for _ in range(1000):
        regex.findall("abc123def456")  # 预编译提升性能


    print("=====================")

    from collections import defaultdict

    log_pattern = re.compile(r"""(?P<timestamp>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\s+(?P<level>\w+)\s+(?P<message>.+) """)

    log_data = """
    2025-04-21 09:15:00 INFO Starting application
    2025-04-21 09:15:01 ERROR Failed to connect to DB
    """
    stats = defaultdict(int)
    for line in filter(None, log_data.strip().split("\n")):

        print(line.strip())
        match = log_pattern.match(line.strip())
        if match:
            stats[match.group("level")] += 1

    print(stats)  # defaultdict(<class 'int'>, {'INFO': 1, 'ERROR': 1})


    print('================sub======')


    def clean_text(text_new):
        # 去除特殊符号
        text_new = re.sub(r"[^\w\s]", "", text_new)
        # 标准化空格
        text_new = re.sub(r"\s+", " ", text_new)
        # 转小写
        return text_new.strip().lower()


    dirty_text = "  Hello,  World!  \nThis is a TEST...  "
    clean = clean_text(dirty_text)
    print(clean)  # "hello world this is a test"